#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>//bool:true\false
#include "sequence_stack.h"

/*初始化栈*/
Sq_Stack_t* InitStack(void)
{
    Sq_Stack_t *new_stack = (Sq_Stack_t *)malloc(sizeof(Sq_Stack_t));
    if (!new_stack)
    {
        perror("null");
        return NULL;
    }

    new_stack->base = (ElemType *)malloc(sizeof(ElemType) * MAX_STACK_SIZE);
    if (new_stack->base == NULL)
    {
        free(new_stack);
        perror("null");
        return NULL;
    }

    new_stack->top = new_stack->base;
    new_stack->size = MAX_STACK_SIZE;
    
    return new_stack;
}

/*销毁栈*/
void DestroyStack(Sq_Stack_t **stack)
{
    if (*stack == NULL)
    {
         perror("null");
        return;
    }

    if ((*stack)->base)
    {
        free((*stack)->base);
    }
    free (*stack);
    *stack = NULL;
}

// void ClearStack(Sq_Stack_t *stack)
// {
//     if (stack == NULL)
//     {
//         perror("null");
//         return;
//     }

//     stack->top = stack->base;
// }

/*是否栈满*/
bool IsFull(Sq_Stack_t *stack)
{
    if ((stack->top - stack->base) / sizeof(ElemType) == stack->size)
    {
        return true;
    }
    
    return false;
}

/*是否空栈*/
bool IsEmpty(Sq_Stack_t *stack)
{
    printf("stack->base = %d\n",stack->base);
    printf("stack->top = %d\n",stack->top);
    if (stack->top == stack->base)
    {
        printf("Empty\n");
        return true;
        /* code */
    }
    else
    {
        printf("!Empty\n");
        return false;
    }
    
}

/*入栈*/
Sq_Stack_t* PushStack(Sq_Stack_t *stack,ElemType *data)
{
    if (IsFull(stack))/*栈满*/
    {
        return stack;
    }
    
    *(stack->top) = *data;
    stack->top ++;
    return stack;
}

/*出栈*/
ElemType* PopStack(Sq_Stack_t *stack)
{
    if (!stack || IsEmpty(stack))/*空栈*/
    {
        return NULL;
    }
    
    return --(stack->top);
}

/*取栈顶元素*/
ElemType* getTop(Sq_Stack_t *stack)
{
    if (!stack || IsEmpty(stack))/*空栈*/
    {
        return NULL;
    }
    return (stack->top - 1);
}

Sq_Stack_t *stack = NULL;

int main(int argc, char const *argv[])
{
    stack = InitStack();

    int a = 1;
    PushStack(stack,&a);
    a = 2;
    PushStack(stack,&a);
    a = 3;
    PushStack(stack,&a);
    a = 4;
    PushStack(stack,&a);
    a = 5;
    PushStack(stack,&a);
    a = 6;
    PushStack(stack,&a);

    PopStack(stack);
    // PopStack(stack);

    //PrintStack(stack);

    ElemType *top = getTop(stack);

    printf("Stack Top = %d\n",(int)*top);
    return 0;
}
